<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="套餐id" prop="changeId" v-show="false">
        <el-input v-model="formData.changeId" placeholder="请输入套餐id" type="hidden" />
      </el-form-item>
      <el-form-item label="套餐" prop="changeName">
        <el-select v-model="formData.changeName" placeholder="请选择套餐" @change="handleChangeSelect">
          <el-option
            v-for="item in packageOptions"
            :key="item.id"
            :label="item.changeName"
            :value="item.changeName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="兑换码" prop="code">
        <el-input disabled v-model="formData.code" placeholder="自动生成" />
      </el-form-item>
      <el-form-item label="兑换码数量" prop="codeNum">
        <el-input-number v-model="formData.codeNum" :min="1" :max="1000" placeholder="请输入兑换码数量" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <dict-tag v-if="formData.customerId" :type="DICT_TYPE.CUSTOMER" :value="formData.customerId" />
        <span v-else>自动填充</span>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CHANGE_CODE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="过期时间" prop="expireDate">
        <el-date-picker
          v-model="formData.expireDate"
          type="date"
          value-format="x"
          placeholder="选择过期时间"
        />
      </el-form-item>
      <el-form-item label="客户id" prop="customerId" v-show="false">
        <el-input v-model="formData.customerId" placeholder="请输入客户id" type="hidden" />
      </el-form-item>
     
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { UserAssetsCodeApi, UserAssetsCodeVO } from '@/api/ai/userassetscode'
import { UserAssetsChangeApi } from '@/api/ai/userassetschange'
import DictTag from '@/components/DictTag/src/DictTag.vue'

/** 用户资源兑换 表单 */
defineOptions({ name: 'UserAssetsCodeForm' })

// 定义套餐选项的接口
interface PackageOption {
  id: number
  customerId: number | null
  trailCount: number
  customerName: string
  changeName: string
  contentDays: number
  trailLeftCount: number
  psCount: number
  psLeftCount: number
  contentCount: number
  contentLeftCount: number
  askCount: number
  askLeftCount: number
  trailUpdateTime: number | null
  psUpdateTime: number | null
  contentEndTime: number | null
  contentStartTime: number | null
  createTime: number
}

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const packageOptions = ref<PackageOption[]>([]) // 套餐选项列表
const formData = ref({
  id: undefined as number | undefined,
  userId: undefined as number | undefined,
  changeId: undefined as number | undefined,
  code: undefined as string | undefined,
  customerName: undefined as string | undefined,
  status: 0 as number | undefined, // 默认设置为0，表示"未使用"状态
  expireDate: undefined as number | undefined,
  customerId: undefined as number | undefined,
  usedDate: undefined as number | undefined,
  userName: undefined as string | undefined,
  changeName: undefined as string | undefined,
  codeNum: 100 as number | undefined, // 默认设置为100个兑换码
})
const formRules = reactive({
  changeName: [{ required: true, message: '请选择套餐', trigger: 'change' }],
  codeNum: [{ required: true, message: '请输入兑换码数量', trigger: 'blur' }],
  expireDate: [{ required: true, message: '请选择过期时间', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 获取套餐列表 */
const getPackageOptions = async () => {
  try {
    console.log('开始获取套餐列表')
    // 使用已定义的API函数获取套餐列表
    const res = await UserAssetsChangeApi.getUserAssetsChangePage({
      pageNo: 1,
      pageSize: 1000
    })
    console.log('套餐列表API返回结果:', res)
    
    // 处理不同的数据结构情况
    if (res.list && Array.isArray(res.list)) {
      // 直接返回了 {list: [...], total: 1} 结构
      packageOptions.value = res.list
      console.log('设置套餐列表成功(直接结构)，数量:', packageOptions.value.length)
    } else if (res.data && res.data.list) {
      // 返回了 {code: 0, data: {list: [...], total: 1}, msg: ""} 结构
      packageOptions.value = res.data.list
      console.log('设置套餐列表成功(嵌套结构)，数量:', packageOptions.value.length)
    } else {
      console.error('API返回数据结构不符合预期:', res)
    }
  } catch (error) {
    console.error('获取套餐列表失败', error)
  }
}

/** 套餐选择后自动填充相关信息 */
const handleChangeSelect = (value: string) => {
  const selectedPackage = packageOptions.value.find(item => item.changeName === value)
  if (selectedPackage) {
    formData.value.changeId = selectedPackage.id
    formData.value.customerId = selectedPackage.customerId ?? undefined
    
    // 从字典中获取客户名称 - 这个字段保留但不再显示在界面上
    if (selectedPackage.customerId) {
      const customerLabel = getDictLabel(DICT_TYPE.CUSTOMER, selectedPackage.customerId)
      formData.value.customerName = customerLabel || selectedPackage.customerName
    } else {
      formData.value.customerName = ''
    }
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取套餐列表
  await getPackageOptions()
  console.log('打开弹窗后的套餐列表:', packageOptions.value)
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserAssetsCodeApi.getUserAssetsCode(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserAssetsCodeVO
    if (formType.value === 'create') {
      await UserAssetsCodeApi.createUserAssetsCode(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserAssetsCodeApi.updateUserAssetsCode(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    changeId: undefined,
    code: undefined,
    customerName: undefined,
    status: 0, // 默认设置为0，表示"未使用"状态
    expireDate: undefined,
    customerId: undefined,
    usedDate: undefined,
    userName: undefined,
    changeName: undefined,
    codeNum: 100, // 默认设置为100个兑换码
  }
  formRef.value?.resetFields()
}
</script>
